from threading import Condition, Thread
import time

from app.services.business.gaolu_diagnose.ind.abstract_ind import RealTimeInfluxDbInd
import logging as log


class CountDownLatch:
    def __init__(self, count):
        self.count = count
        self.condition = Condition()

    def await(self):
        try:
            self.condition.acquire()
            while self.count > 0:
                self.condition.wait(5)
        finally:
            self.condition.release()

    def countDown(self):
        try:
            self.condition.acquire()
            self.count -= 1
            self.condition.notifyAll()
        finally:
            self.condition.release()


class SubThread(Thread):
    def __init__(self, name, latch: CountDownLatch, params,func):
        Thread.__init__(self)
        self.name = name
        self.latch = latch
        self.params = params
        self.result = 0
        self.func = func

    def run(self):
        self.func(self)
        self.latch.countDown()


if __name__ == '__main__':
    class SubThread2(Thread):
        def __init__(self, name, latch):
            Thread.__init__(self)
            self.name = name
            self.latch = latch

        def run(self):
            print("finishing %s" % self.name)
            time.sleep(3)
            self.latch.countDown()


    latch = CountDownLatch(3)
    print("start main thread")
    # thread1 = SubThread("thread first", latch)
    # thread2 = SubThread("thread second", latch)
    # thread3 = SubThread("thread third", latch)
    # thread1.start()
    # thread2.start()
    # thread3.start()
    latch.await()
    print("stop main thread")
